__author__ = 'Oren'

import json
import datetime
from model_att import Att

from google.appengine.ext import ndb
from model_PC import PC
from model_parent import Parent



class Child (ndb.Model):
    """ Models an individual child entry with content and id (key)"""

    first_name =    ndb.StringProperty()
    last_name =     ndb.StringProperty()
    child_id =          ndb.StringProperty()
    gender =        ndb.StringProperty()
    date_of_birth =  ndb.DateProperty()
    address =       ndb.StringProperty()
    phone_number =         ndb.StringProperty()
    KG_id =          ndb.StringProperty()
    avatar =       ndb.BlobProperty()


    def get_full_name(self):
        return self.first_name + " " + self.last_name


    @staticmethod
    def create_child_from_json(child_info_json):
        """ Create and put a new child in db, make sure child id is not exists """
        data = json.loads(child_info_json)
        year, month, day = map(int, data.get("date_of_birth").split('-'))
        child = Child(first_name =   data.get("first_name"),
                      last_name =        data.get("last_name"),
                      child_id =        data.get("child_id"),
                      gender =          data.get("gender"),
                      date_of_birth =     datetime.date(day=day, month=month, year=year),
                      address =         data.get("address"),
                      phone_number =           str(data.get("phone_number")),
                      KG_id =            data.get("KG_id"))
        check_child_exists = Child.query(Child.child_id == data.get("child_id")).get()
        if check_child_exists != None:
            return -1
        else:
            return child.put()

    @staticmethod
    def update_child_from_json(info_json):
        """ Update a child info in db, return -1 if child does not exists """
        data = json.loads(info_json)
        year, month, day = map(int, data.get("date_of_birth").split('-'))
        child = Child(first_name =   data.get("first_name"),
                      last_name =        data.get("last_name"),
                      child_id =        data.get("child_id"),
                      gender =          data.get("gender"),
                      date_of_birth =     datetime.date(day=day, month=month, year=year),
                      address =         data.get("address"),
                      phone_number =           str(data.get("phone")),
                      KG_id =            data.get("KG_id"))
        check_child_exists = Child.query(Child.child_id == data.get("child_id")).get()
        if check_child_exists is not None:
            check_child_exists.key.delete()
            child.put()
            return 1
        else:
            return -1

    @staticmethod
    def delete_child_by_id(given_child_id):
        """ Delete a child from db, by child id, if child id doesnt exists return -1 """
        check_child_exists = Child.query(Child.child_id == given_child_id).get()
        if check_child_exists is None:
            return -1
        else:
            check_child_exists.key.delete()
            PC.delete_entities_by_child_id(given_child_id)
            return 1

    @staticmethod
    def get_child_info(given_child_id):
        """ returns info about a child with a given child id """
        check_child_exists = Child.query(Child.child_id == given_child_id).get()
        if check_child_exists is None:
            return -1
        else:
            # get parents info
            parents_ids = PC.get_parents_id_by_child_id(check_child_exists.child_id)
            parents_info = []
            for p_id in parents_ids:
                parents_info.append(json.loads(Parent.get_parent_info(p_id)))

            date = str(check_child_exists.date_of_birth)
            year, month, day = date.split('-')
            rev_date = day + '-' + month + '-'+ year
            data = {"first_name" : check_child_exists.first_name,
                    "last_name" : check_child_exists.last_name,
                    "child_id" : check_child_exists.child_id,
                    "gender" : check_child_exists.gender,
                    "date_of_birth" : rev_date,
                    "address": check_child_exists.address,
                    "phone_number": check_child_exists.phone_number,
                    "KG_id": check_child_exists.KG_id,
                    "parent1_first_name": parents_info[0].get("first_name"),
                    "parent1_last_name": parents_info[0].get("last_name"),
                    "parent1_phone_number": parents_info[0].get("phone_number"),
                    "parent1_email_address": parents_info[0].get("email_address")}
            # adding second parent (if exist)
            if len(parents_info) > 1:
                data ["parent2_first_name"] = parents_info[1].get("first_name")
                data ["parent2_last_name"] = parents_info[1].get("last_name")
                data ["parent2_phone_number"] = parents_info[1].get("phone_number")
                data ["parent2_email_address"] = parents_info[1].get("email_address")
            data_json = json.dumps(data)
            return data_json


    @staticmethod
    def get_children_in_KG_id(required_KG_id):
        """ Returns list with all ids of children in kindergarten with given id"""
        childs = ndb.gql("SELECT * FROM Child WHERE KG_id = :teacher ORDER BY last_name", teacher=str(required_KG_id))
        child_list = []
        for child in childs:
            child_list.append(child.child_id)
        # child_list.reverse()
        return child_list


    @staticmethod
    def create_children_dictionary(id_list):
        child_dic = {}
        for child_id in id_list:
            child_dic[child_id] = Child.convert_child_id_to_full_name(child_id)
        return child_dic

    @staticmethod
    def convert_child_id_to_full_name(child_id_given):
        """ Returns full name of child with given id """
        child = Child.query(Child.child_id == child_id_given).get()
        return child.get_full_name()

    @staticmethod
    def get_name_and_att_from_child_id(child_id_given, date_given):
        """ Returns json with full name and att of specific child (by his id and date) """
        j = {"child_id": child_id_given, "date": date_given}
        att_json = json.dumps(j)
        att = Att.get_att_of_child_by_child_id_and_date(att_json)
        data = {"full_name": Child.convert_child_id_to_full_name(child_id_given),
                "att": att}
        data_json = json.dumps(data)
        return data_json

    @staticmethod
    def get_KG_id_by_given_child_id_in_json(data_json):
        """ Returns KG id of child by his id """
        data = json.loads(data_json)
        child = Child.query(Child.child_id == data.get("child_id")).get()
        details = {'KG_id': child.KG_id}
        details_json = json.dumps(details)
        return details_json



